package al.jdbc.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import al.jdbc.dpbridge.DataSource;
import alOmrane.jdbc.beans.Moy_env;

public class Moy_envDAO {
	private Connection db;
	@SuppressWarnings("unused")
	private DataSource ds;
	private Statement sql;
	
	public Moy_envDAO(DataSource ds){
		db = ds.getConnection();
		this.ds = ds;
		try {
			sql = db.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public List<Moy_env> findAll(){
		List<Moy_env> mes = new ArrayList<Moy_env>();
		try {
			String query = "SELECT * FROM moy_env";

			ResultSet rs = sql.executeQuery(query);
			while(rs.next()){
				Moy_env me = new Moy_env(Integer.parseInt(rs.getString(1)),
						rs.getString(2));
				mes.add(me);
			}
			return mes;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public Moy_env findById(int id){
		try {
			String query = "SELECT * FROM moy_env" +
					" WHERE id_moy_env="+id;

			ResultSet rs = sql.executeQuery(query);
			rs.next();
			Moy_env me = new Moy_env(Integer.parseInt(rs.getString(1)),
					rs.getString(2));
			return me;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	public boolean insert(Moy_env m){
		try{
			StringBuffer sb = new StringBuffer("INSERT INTO moy_env VALUES (" +
					"'"+m.getId()+"'," +
					"'"+m.getDesi_moy_env()+"');");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			System.out.println(ex.getMessage());
			return false;
		}
	}
	public int incrementEngine(){
		try {
			String query = "SELECT Max(id_moy_env ) FROM moy_env";

			ResultSet rs = sql.executeQuery(query);
			rs.next();
			return Integer.parseInt((rs.getString(1)==null)?"0":rs.getString(1))+1;
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
}
